<template>
  <div class='container'>
    <el-dialog :title="title" :visible="showDialog" @close="btnCancel" width="400px">
      <el-form ref="formDate" :model="formDate" :rules="rules">
        <el-form-item label="学科名称" prop="subjectName" label-width="100px">
        <el-input v-model="formDate.subjectName" placeholder="请输入学科名称"></el-input>
      </el-form-item>
      <el-form-item label="是否显示" label-width="100px">
        <el-switch
        v-model="formDate.isFrontDisplay"
        :active-value="1"
        :inactive-value="0"
        active-color="#13ce66"
        ></el-switch>
      </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-row type="flex" justify="center">
        <el-button size="small" @click="btnCancel">取消</el-button>
        <el-button type="primary" size="small" @click="confirm">确定</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>

import { addSubject, getSubjectDetail, updateSubject } from '@/api/hmmm/subjects'

export default {
  name: 'SubjectDialog',
  props: {
    showDialog: {
      type: Boolean,
      require: false
    }
  },
  data () {
    return {
      formDate: {
        subjectName: '',
        isFrontDisplay: null,
        id: null
      },
      rules: {
        subjectName: [{ required: true, message: '请输入学科名称', trigger: 'blur' }]
      }
    }
  },
  computed: {
    title () {
      return this.formDate.id ? '编辑学科' : '新增学科'
    }
  },
  methods: {
    btnCancel () {
      this.formDate = {
        subjectName: '',
        isFrontDisplay: '1',
        id: null
      }
      this.$emit('update:showDialog', false)
    },
    async confirm () {
      try {
        await this.$refs.formDate.validate()
        if (this.formDate.id) {
          await updateSubject(this.formDate)
          this.$message.success('编辑成功')
        } else {
          await addSubject(this.formDate)
          this.$message.success('添加成功')
        }
        this.$emit('updateList')
        this.btnCancel()
      } catch (error) {
        console.log(error)
      }
    },
    async subDetail (id) {
      const res = await getSubjectDetail(id)
      console.log(res)
      this.formDate.subjectName = res.data.subjectName
      this.formDate.isFrontDisplay = res.data.isFrontDisplay
      this.formDate.id = res.data.id
    }
  }
}
</script>

<style scoped lang='less'></style>
